package com.ass.flink.utils;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.conf.YarnConfiguration;

import java.util.EnumSet;
import java.util.List;

public class YarnUtil {

    public static YarnClient createYarnClient(){
        Configuration conf = new YarnConfiguration();
        YarnClient yarnClient = YarnClient.createYarnClient();
        yarnClient.init(conf);
        yarnClient.start();
        return yarnClient;
    }

    /**
     * @describe：获得hadoop里面所有yarn调度，根据状态
     * @author：李勇
     * @date：2024/4/17
     * @param status 参数之YarnApplicationState的枚举值 eg:YarnApplicationState.RUNNING.name()
     * @return：java.util.List<org.apache.hadoop.yarn.api.records.ApplicationReport>
     */
    public static List<ApplicationReport> getYarnByStatus(String status){
        YarnClient yarnClient = createYarnClient();
        try {
            List<ApplicationReport> applications = yarnClient.getApplications(EnumSet.of(YarnApplicationState.valueOf(status)));
            return applications;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            yarnClient.stop();
        }
    }

    public static ApplicationReport getApplicationReport(String applicationId){
        // 将 String 转换为 ApplicationId
        YarnClient yarnClient = createYarnClient();
        try {
            return yarnClient.getApplicationReport(ApplicationId.fromString(applicationId));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            yarnClient.stop();
        }
    }

    public static void main(String[] args) {
        String a = "http://hdfs-node-03:48088/proxy/application_1728347338709_0001/";
        String[] split = a.split("/");
        System.out.println(split);
    }


}
